module.exports = (app) => {
  const express = require('express')
  const admin = express.Router({
    /**合并url参数。把父级app.use中的参数合并到router实例中，
     *这样才能在接口中通过res.params.resource获取到 app.use父级中的resource动态参数
     */
    mergeParams: true
  })
  // const Category = require('../../models/Category')

  admin.post('/', async (req, res) => {
    await req.Model.create(req.body)
    res.send({
      data: '',
      meta: {
        status: 0,
        msg: '创建成功'
      }
    })
  })

  admin.get('/', async (req, res) => {
    const result = await req.Model.find().populate('parents')
    // console.log(result)
    res.send({
      data: result,
      meta: {
        status: 0,
        msg: '获取成功'
      }
    })
  })

  admin.get('/:id', async (req, res) => {
    const result = await req.Model.findById(req.params.id)
    res.send({
      data: result,
      meta: {
        status: 0,
        msg: '获取成功'
      }
    })
  })

  admin.put('/:id', async (req, res) => {
    await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send({
      data: '',
      meta: {
        status: 0,
        msg: '更改成功'
      }
    })
  })

  admin.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id)
    res.send({
      data: '',
      meta: {
        status: 0,
        msg: '删除成功'
      }
    })
  })

  // 将路由对象与请求路径进行匹配。 (rest代表的是通用的接口；resource用来动态获取接口地址，如category)
  app.use('/api/admin/rest/:resource', async (req, res, next) => {
    const modelName = require('inflection').classify(req.params.resource)
    req.Model = require(`../../models/${modelName}`)
    next()
  }, admin)
}